﻿using System.Data;
using System.Data.SqlClient;
using System;

namespace Adams.Web.Areas.MyAdams.Data.Profile
{
    public static class Email
    {
        public static Adams.Web.Areas.MyAdams.Models.Profile.Email.PageLoad PageLoad(int memberId)
        {
            var data = new Adams.Web.Areas.MyAdams.Models.Profile.Email.PageLoad();

            using (SqlDataReader dr = Adams.Web.Data.DB.RunDataReader(@"
SELECT M.*
FROM Membership.Members M
WHERE M.MemberID = @MemberID
", CommandType.Text,
    Adams.Web.Data.DB.CreateParameter("@MemberID", memberId)))
            {
                if (dr.HasRows)
                {
                    dr.Read();
                    data.Member = Adams.Web.Data.DB.InitFromReader<Adams.Shared.Entities.Membership.Member>(dr, new Adams.Web.Data.ColMap { NameInDb = "MemberID", NameInObject = "ID" });
                }
            }

            return data;
        }

        public static Adams.Web.Areas.MyAdams.Models.Profile.Email.MemberInfo GetMemberInfo(int memberId, string email)
        {
            var data = new Adams.Web.Areas.MyAdams.Models.Profile.Email.MemberInfo();

            using (SqlDataReader dr = Adams.Web.Data.DB.RunDataReader(@"
IF (@MemberID > 0)
BEGIN
    SELECT *
    FROM Membership.Members
    WHERE MemberID = @MemberID
END

SELECT COUNT(*) AS Count
FROM Membership.Members
WHERE Email = @Email
", CommandType.Text,
                Adams.Web.Data.DB.CreateParameter("@MemberID", memberId),
                Adams.Web.Data.DB.CreateParameter("@Email", email)))
            {
                if (memberId > 0)
                {
                    dr.Read();
                    data.Email = dr["Email"].DbString();
                    dr.NextResult();
                }
                dr.Read();
                data.Exists = dr["Count"].DbInt() > 0;
            }

            return data;
        }

        public static void SaveEmail(int memberId, string email)
        {
            Adams.Web.Data.DB.Run(@"
UPDATE Membership.Members SET
    Email = @Email, IsEmailConfirmed = 0
WHERE MemberID = @MemberID
", CommandType.Text,
                    Adams.Web.Data.DB.CreateParameter("@MemberID", memberId),
                    Adams.Web.Data.DB.CreateParameter("@Email", email));
        }
    }
}
